package org.jeecg.common.es;

import cn.hutool.core.lang.Assert;
import com.google.common.collect.Lists;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.jeecg.common.es.annotation.EsAlias;
import org.jeecg.common.es.entity.EsEntity;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;

import java.util.List;

/**
 * @author wangzun1.vendor@sensetime.com
 * @Description:
 * @date 2022/8/10
 */

public class EsIndexUtil {
    private static final String TENANT_ID_PLACEHOLDER = "\\{tenant_id\\}";

    public EsIndexUtil() {}

    public static String getRealAlias(Class<? extends EsEntity> clazz) {
        if (clazz.isAnnotationPresent(EsAlias.class)) {
            EsAlias alias = (EsAlias)clazz.getAnnotation(EsAlias.class);
            String aliasName = alias.aliasName();
            Assert.notBlank(aliasName,
                "Unknown aliasName. Make sure the aliasName is defined. e.g @EsAlias(aliasName=\"foo_{tenant_id}\")");
            return aliasName.replaceAll("\\{tenant_id\\}", getTenantId());
        } else {
            return null;
        }
    }

    public static IndexCoordinates aliasCoordinates(Class<? extends EsEntity> clazz) {
        return IndexCoordinates.of(new String[] {getRealAlias(clazz)});
    }

    public static boolean existIndex(GetIndexResponse indexResponse, String index) {
        if (indexResponse == null) {
            return false;
        } else {
            List<String> indices = Lists.newArrayList(indexResponse.getIndices());
            return indices.contains(index);
        }
    }

    public static boolean existAlias(GetIndexResponse indexResponse, String alias) {
        return indexResponse != null && indexResponse.getAliases() != null
            ? indexResponse.getAliases().containsKey(alias) : false;
    }

    public static String getTenantId() {
        return "default";
    }
}
